package org.rcy.ruicingmarket.common.utils;

import org.rcy.ruicingmarket.common.base.CollectionBeanUtilsCallBack;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

public class CollectionBeanUtils extends BeanUtils {
    public CollectionBeanUtils() {
    }

    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
        return copyListProperties(sources, target, null);
    }

    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, CollectionBeanUtilsCallBack<S, T> callBack) {
        List<T> list = new ArrayList<>(sources.size());
        Iterator iterator = sources.iterator();
        while (iterator.hasNext()) {
            S source = (S) iterator.next();
            T t = target.get();
            copyProperties(source, t);
            list.add(t);
            if (callBack != null) {
                callBack.callBack(source, t);
            }
        }
        return list;
    }

    public static <S, T> Set<T> copySetProperties(Set<S> sources, Supplier<T> target) {
        return copySetProperties(sources, target, null);
    }

    public static <S, R, T> Map<S, T> copyMapProperties(Map<S, R> sources, Supplier<T> target) {
        return copyMapProperties(sources, target, null);
    }

    public static <S, T> Set<T> copySetProperties(Set<S> sources, Supplier<T> target, CollectionBeanUtilsCallBack<S, T> callBack) {
        Set<T> set = new HashSet<>(sources.size());
        Iterator iterator = sources.iterator();
        while (iterator.hasNext()) {
            S source = (S) iterator.next();
            T t = target.get();
            copyProperties(source, t);
            set.add(t);
            if (callBack != null) {
                callBack.callBack(source, t);
            }
        }
        return set;
    }

    public static <S, R, T> Map<S, T> copyMapProperties(Map<S, R> sources, Supplier<T> target, CollectionBeanUtilsCallBack<R, T> callBack) {
        Map<S, T> map = new HashMap<>(sources.size());
        Set<S> s = sources.keySet();
        Iterator iterator = s.iterator();
        while (iterator.hasNext()) {
            S key = (S) iterator.next();
            R r = sources.get(key);
            T t = target.get();
            copyProperties(r, t);
            map.put(key, t);
            if (callBack != null) {
                callBack.callBack(r, t);
            }
        }
        return map;
    }
}
